package com;

import java.io.IOException;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Component;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;


@Component // 服务过滤
public class TestFilter extends ZuulFilter{

	/**
	 * 这里可以写逻辑判断，是否要过滤，本文true,永远过滤。
	 */
	@Override
	public boolean shouldFilter() {
		return true;
	}

	/**
	 * 过滤器的具体逻辑。
	 */
	@Override
	public Object run() throws ZuulException {
		RequestContext context = RequestContext.getCurrentContext();
		HttpServletRequest request = context.getRequest();
		String token = request.getParameter("token");
		if(Objects.isNull(token) || token.trim().isEmpty()) {
			context.setResponseStatusCode(401);
			context.setSendZuulResponse(false);
			try {
				context.getResponse().getWriter().println("token is null");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 返回一个字符串代表过滤器的类型，在zuul中定义了四种不同生命周期的过滤器类型，具体如下：
	 * 路由之前：pre
	 * 路由之时：route
	 * 路由之后：post
	 * 发生错误：error
	 */
	@Override
	public String filterType() {
		return "pre";
	}

	/**
	 * 过滤顺序
	 */
	@Override
	public int filterOrder() {
		return 0;
	}
	

}
